package cn.tedu.pojo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;

//是C层,控制层,用来接受请求和给出响应
@RestController
@RequestMapping("stu")
public class StuController {
    @RequestMapping("add")
    public Object add(Student s) throws Exception {
        //TODO 利用jdbc,实现入库
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url="jdbc:mysql:///cgb2106?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url,"root","root");
        //获取传输器
        String sql = "insert into tb_student values(null,?,?,?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        //给SQL设置参数
        ps.setObject(1,s.getName());
        ps.setObject(2,s.getAge());
        ps.setObject(3,s.getSex());

//s.getHobby()得到一个数组,不能直接存入数据库,需要变成串入库
        ps.setObject(4, Arrays.toString( s.getHobby() ) ) ;
        ps.setObject(5,s.getEdu());
        ps.setObject(6,s.getIntime());
        //执行SQL
        ps.executeUpdate();//执行增删改的SQL
        System.out.println("数据插入成功!");
        return s;
    }

}

